<template>
  <div class="inner-chunk">
    <div class="w-full h-screen" ref="chartDom"></div>

    <!-- 图标说明卡片 -->
    <div class="card absolute bottom-5 left-5 bg-base-100 shadow-lg z-50">
      <div class="card-body p-3">
        <div class="flex flex-col gap-2">
          <div class="flex items-center">
            <img :src="b1" class="w-6 h-6 mr-2" alt="企业" />
            <span class="text-sm">企业</span>
          </div>
          <div class="flex items-center">
            <img :src="b6" class="w-6 h-6 mr-2" alt="项目" />
            <span class="text-sm">项目</span>
          </div>
          <div class="flex items-center">
            <img :src="b7" class="w-6 h-6 mr-2" alt="资源" />
            <span class="text-sm">资源</span>
          </div>
          <div class="flex items-center">
            <img :src="b8" class="w-6 h-6 mr-2" alt="资源" />
            <span class="text-sm">建筑</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import chanye from "@/assets/images/bar.png";
import ziyuan from "@/assets/images/bar-2.png";
import kongjian from "@/assets/images/bar-3.png";
import xiangmu from "@/assets/images/bar-1.png";
import b4 from "@/assets/images/4.png";
import b2 from "@/assets/images/2.png";
import b3 from "@/assets/images/3.png";
import b5 from "@/assets/images/5.png";
import b1 from "@/assets/images/9.png";
import b6 from "@/assets/images/8.png";
import b7 from "@/assets/images/icon.png";
import b8 from "@/assets/images/icon2.png";
import arrow from "@/assets/images/arrow.png";
import { useCompanyStore } from "@/stores/company";

const emit = defineEmits(["info-window-btn-click"]);

const chartDom = ref(); // dom
const selectedData = ref([]);
let customOverlay = null;
const iconSrcMap = {
  emp: b1, //企业
  resource: b7, //资源
  scope: b8, //建筑
  project: b6, //项目
};
function getIconSrcByType(type) {
  return iconSrcMap[type];
}

const companyStore = useCompanyStore();

const qaData = computed(() => companyStore.companyList);
const companyState = companyStore;
// const qaData = ref([]);

let map;
let iconMap = {};

const config = useRuntimeConfig();
// for (const key in companyState.company) {
//   if (companyState.company.hasOwnProperty(key)) {
//     const companies = companyState.company[key];
//     if (companies) {
//       companies.forEach((company) => {
//         qaData.value.push({
//           ...company,
//           __key: key // 添加临时键名标识
//         });
//       });
//     }
//   }
// }
const loadBaiDuSDK = () => {
  return new Promise((resolve) => {
    const mapKey = config.public.MAP_APP_KEY;
    // 创建script标签
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=${mapKey}&callback=onBMapCallback`;
    document.body.appendChild(script);
    // 添加回调函数
    window.onBMapCallback = () => {
      console.log("百度地图脚本加载完成");
      resolve(true);
    };
  });
};

// 创建按钮
const createButton = (html, className, eventHandler) => {
  const button = document.createElement("button");
  button.className = className;
  button.innerHTML = html;
  button.addEventListener("click", eventHandler);
  return button;
};

const showAnalysis = (type, item) => {
  console.log("showAnalysis");

  emit("info-window-btn-click", type, item);
};

/**获取地图信息 */
onMounted(async () => {
  await loadBaiDuSDK();

  // 定义不同类型的图标
  iconMap = {
    emp: new BMap.Icon(chanye, new BMap.Size(32, 45)),
    project: new BMap.Icon(xiangmu, new BMap.Size(32, 45)),
    resource: new BMap.Icon(ziyuan, new BMap.Size(32, 45)),
    scope: new BMap.Icon(kongjian, new BMap.Size(32, 45)),
  };
  // 自定义覆盖物类
  function CustomOverlay(point, item) {
    this._point = point;
    this._item = item;
  }

  CustomOverlay.prototype = new BMap.Overlay();

  CustomOverlay.prototype.initialize = function (map) {
    this._map = map;
    const div = (this._div = document.createElement("div"));
    div.style.position = "absolute";
    div.style.width = "200px";
    div.style.height = "180px";
    div.style.backgroundColor = "white";
    div.style.border = "1px solid #ccc";
    div.style.borderRadius = "10px";
    div.style.boxShadow =
      "0 5px 15px rgba(0, 0, 0, 0.4), 0 2px 3px rgba(0, 0, 0, 0.2)";
    div.style.padding = "10px";
    div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);

    // 动态生成 HTML 内容
    const header = document.createElement("div");
    header.className = "flex items-center";
    const img = document.createElement("img");
    img.src = getIconSrcByType(this._item.__key);
    img.width = "16";
    img.height = "16";
    img.className = "w-6 h-6 inline mr-[5px]";
    img.alt = "分析图标";
    header.appendChild(img);

    const span = document.createElement("span");
    span.textContent = this._item.name;
    span.className =
      "font-bold text-sm text-ellipsis whitespace-nowrap overflow-hidden inline-block";
    header.appendChild(span);
    div.appendChild(header);

    const container = document.createElement("div");
    container.className = "flex flex-col gap-1 mt-2 text-sm";

    if (this._item.__key === "emp") {
      div.style.height = "230px";
      container.appendChild(
        createButton(
          `<img  src="${b2}" width="16" height="16" class="w-6 h-6 " alt="分析图标">
        <span class="ml-2 text-blue-800">产业链图谱</span>`,
          "cursor-pointer px-4 py-2 bg-blue-100  text-white rounded-lg hover:bg-blue-200 flex items-center",
          () => showAnalysis("产业图谱分析", this._item)
        )
      );
    }
    if (this._item.__key === "emp" || this._item.__key === "scope") {
      container.appendChild(
        createButton(
          ` <img src="${b3}" width="16" height="16" class="w-6 h-6 " alt="分析图标">
        <span class="ml-2 text-green-800"">招商建议</span>`,
          "cursor-pointer px-4 py-2 bg-green-100 text-white rounded-lg hover:bg-green-200 flex items-center",
          () => showAnalysis("招商建议", this._item)
        )
      );
    }
    if (this._item.__key === "project" || this._item.__key === "resource") {
      div.style.height = "140px";
    }
    container.appendChild(
      createButton(
        `<img src="${b4}" width="16" height="16" class="w-6 h-6 " alt="分析图标">
        <span class="ml-2 text-orange-800">数据分析</span>`,
        "cursor-pointer px-4 py-2 bg-orange-100 text-white rounded-lg hover:bg-orange-200 flex items-center",
        () => showAnalysis("数据分析", this._item)
      )
    );
    container.appendChild(
      createButton(
        `<img src="${b5}" width="16" height="16" class="w-6 h-6 " alt="分析图标">
        <span class="ml-2 text-purple-800"">自由对话</span>`,
        "cursor-pointer px-4 py-2 bg-purple-100 text-white rounded-lg hover:bg-purple-200 flex items-center",
        () => showAnalysis("自由对话", this._item)
      )
    );
    div.appendChild(container);

    const imgArrow = document.createElement("img");
    imgArrow.src = arrow;
    imgArrow.width = "8";
    imgArrow.height = "8";
    imgArrow.alt = "箭头图标";
    imgArrow.className =
      "absolute bottom-[-25px] left-1/2 transform -translate-x-1/2 w-4 h-4";
    div.appendChild(imgArrow);

    map.getPanes().markerPane.appendChild(div);
    return div;
  };

  CustomOverlay.prototype.draw = function () {
    const pixel = this._map.pointToOverlayPixel(this._point);
    this._div.style.left = pixel.x - 102 + "px";

    if (this._item.__key === "emp") {
      this._div.style.top = pixel.y - 275 + "px";
    } else if (
      this._item.__key === "project" ||
      this._item.__key === "resource"
    ) {
      this._div.style.top = pixel.y - 185 + "px";
    } else if (this._item.__key === "scope") {
      this._div.style.top = pixel.y - 225 + "px";
    }
  };
  // 为标记添加点击事件
  //   marker.addEventListener("click", () => {
  //     map.openInfoWindow(infoWindow, point); // 点击标记时打开信息窗口
  //     selectedData.value = item; // 存储当前点击的点位数据
  //     console.log("当前点击的点位数据：", selectedData.value);
  //   });
  // };
  // 初始化地图
  const getMap = () => {
    map = new BMap.Map(chartDom.value);
    const centerPoint = new BMap.Point(106.713, 26.573);
    map.centerAndZoom(centerPoint, 13);
    map.enableScrollWheelZoom(true);
  };

  getMap();

  // 清除地图上所有覆盖物
  const clearOverlays = () => {
    map?.clearOverlays();
  };
  watch(
    qaData,
    () => {
      clearOverlays();
      qaData.value.forEach((item) => {
        const point = new BMap.Point(item.longitude, item.latitude);
        const marker = new BMap.Marker(point, {
          icon: iconMap[item.__key], // 根据类型设置图标
        });
        map.addOverlay(marker);

        // const customOverlay = new CustomOverlay(point, item);
        // map.addOverlay(customOverlay);

        // 为标记添加点击事件
        marker.addEventListener("click", () => {
          if (customOverlay) {
            map.removeOverlay(customOverlay);
          }

          // 创建新的自定义覆盖物
          customOverlay = new CustomOverlay(point, item);
          map.addOverlay(customOverlay);

          // 显示覆盖物
          customOverlay.draw();

          // 将地图中心移动到标记位置
        });
      });
    },
    {
      immediate: true,
      deep: true,
    }
  );

  const handleClick = (e) => {
    if (customOverlay) {
      map.removeOverlay(customOverlay);
    }
  };

  document.addEventListener("click", handleClick, {
    capture: true,
  });

  $eventBus.on("locationClick", (locationInfo) => {
    document.removeEventListener("click", handleClick);
    const { longitude, latitude } = locationInfo;

    const point = new BMap.Point(longitude, latitude);
    map.setCenter(point);
    customOverlay = new CustomOverlay(
      point,
      Object.assign(locationInfo, {
        __key: "emp",
        name: locationInfo.enterpriseName,
      })
    );
    map.addOverlay(customOverlay);

    requestAnimationFrame(() => {
      document.addEventListener("click", handleClick, {
        capture: true,
      });
    });
  });
});
</script>

<style scoped>
/* 删除之前的CSS样式 */
</style>
